package socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;

/**
 * 服务端
 */
public class UDPDictServer {
    //1. 创建套接字
    //2. 接收数据
    //3. 处理数据
    //4. 显示数据
    public DatagramSocket socket = null;
    public HashMap<String,String> dictMap = new HashMap<>();

    //服务端, 需要指定端口号
    public UDPDictServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
        dictMap.put("cat","猫");
        dictMap.put("dog","狗");
        dictMap.put("pig","猪");
        dictMap.put("fox","狐狸");
        dictMap.put("frog","青蛙");
    }

    public void start() throws IOException {
        System.out.println("服务端已启动, 等待接收数据...");
        /**
         * void receive(DatagramPacket p)
         *  DatagramPacket: 数据报
         */
        /**
         * DatagramPacket(byte buf[], int length)
         * 参数说明
         * buf: 接收数据的数组, 类似于食堂打饭的餐盘
         * length: 接收数据的长度
         */
        while (true) {
            byte buf[]  = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf,buf.length);
            socket.receive(packet);
            //处理数据
            String request = new String(packet.getData(),0,packet.getLength(),
                    "UTF-8");

//            System.out.printf("接收到客户端的数据:[%s:%d]:%s\n",packet.getAddress().getHostName(),
//                    packet.getPort(),request);
            String response = process(request);
            //发送给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,packet.getSocketAddress());
            socket.send(responsePacket);

            System.out.printf("接收到客户端的数据:[%s:%d]:%s, 返回数据:%s\n",packet.getAddress().getHostName(),
                    packet.getPort(),request,response);
        }

    }

    private String process(String request) {
        return dictMap.getOrDefault(request,"无法翻译");
    }

    public static void main(String[] args) throws IOException {
        UDPDictServer server = new UDPDictServer(9090);
        server.start();
    }

}
